package org.zty.common;

public class Page {
	public static final int DEFAULT_PAGE_SIZE = 25;
	public static final int DEFAULT_PAGE_INDEX = 1;

	private int pageIndex;
	private int pageSize;
	private long totalCount;
	private int pageCount;
	private boolean hasNext;
	private boolean hasPrevious;

	public Page(int pageIndex, int pageSize) {
		// check:
		if (pageIndex < 1)
			pageIndex = 1;
		if (pageSize < 1)
			pageSize = 1;
		this.pageIndex = pageIndex;
		this.pageSize = pageSize;
	}

	public Page(int pageIndex) {
		this(pageIndex, DEFAULT_PAGE_SIZE);
	}
	
	public Page(){
		this(DEFAULT_PAGE_INDEX,DEFAULT_PAGE_SIZE);
	}

	public int getPageIndex() {
		if(pageIndex < 1)
			pageIndex = 1;
		return pageIndex;
	}

	public int getPageSize() {
		return pageSize;
	}

	public int getPageCount() {
		return pageCount;
	}

	public long getTotalCount() {
		return totalCount;
	}

	public int getFirstResult() {
		return (pageIndex - 1) * pageSize;
	}

	public boolean getHasPrevious() {
		hasPrevious = pageIndex > 1;
		return hasPrevious;
	}

	public boolean getHasNext() {
		hasNext = pageIndex < pageCount;
		return hasNext;
	}

	public void setTotalCount(long totalCount) {
		this.totalCount = totalCount;
		pageCount = (int)totalCount / pageSize
				+ (totalCount % pageSize == 0 ? 0 : 1);
		// adjust pageIndex:
		if (totalCount == 0) {
			if (pageIndex != 1)
				pageIndex = 1;
				//throw new IndexOutOfBoundsException("Page index out of range.");
		} else {
			if (pageIndex > pageCount)
				pageIndex = pageCount;
				//throw new IndexOutOfBoundsException("Page index out of range.");
		}
	}

	public boolean isEmpty() {
		return totalCount == 0;
	}

	public void setPageIndex(int pageIndex) {
		this.pageIndex = pageIndex;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	} 
	
	public int getPageStartIndex(){
		if(this.pageIndex <= 1){
			return 1;
		}
		else {
			return (pageIndex-1) * pageSize+1;
		}
	}

}
